package com.example.forwardmessages

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Telephony
import android.telephony.SmsMessage
import android.util.Log
import android.widget.Toast
import android.telephony.SubscriptionManager
import android.telephony.SubscriptionInfo
import java.lang.reflect.Method
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest
import java.util.concurrent.TimeUnit

/**
 * SMS广播接收器，用于监听新收到的短信并触发邮件发送
 */
class SMSBroadcastReceiver : BroadcastReceiver() {
    private val TAG = "SMSBroadcastReceiver"
    
    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "接收到短信广播")
        
        // 记录Intent的详细信息，包括action、data和所有extra参数
        Log.d(TAG, "Intent信息 - Action: ${intent.action}")
        Log.d(TAG, "Intent信息 - Data: ${intent.data}")
        
        // 记录所有Intent额外数据
        val extras = intent.extras
        if (extras != null) {
            val keys = extras.keySet()
            val stringBuilder = StringBuilder("Intent所有额外数据:\n")
            for (key in keys) {
                val value = extras.get(key)
                stringBuilder.append("$key: $value\n")
            }
            Log.d(TAG, stringBuilder.toString())
        } else {
            Log.d(TAG, "Intent不包含额外数据")
        }
        
        // 检查是否是短信接收广播
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION == intent.action) {
            Log.d(TAG, "检测到新短信")
            
            // 在Android 4.4及以上版本使用Telephony.Sms类解析短信
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent)
                for (message in messages) {
                    val sender = message.originatingAddress
                    val messageBody = message.messageBody
                    val timestamp = System.currentTimeMillis()
                    val time = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())
                    
                    // 获取SIM卡信息
                    val simInfo = getSimInfo(context, intent)
                    Log.d(TAG, "新短信 - 发送者: $sender, 内容: $messageBody, SIM卡信息: $simInfo")
                    
                    // 使用WorkManager调度邮件发送任务
                    scheduleEmailForwarding(context, sender, messageBody, time, simInfo)
                    
                    // 只处理第一条短信即可，避免重复发送邮件
                    break
                }
            } else {
                // 旧版Android系统的处理方式
                val bundle = intent.extras
                if (bundle != null) {
                    val pdus = bundle["pdus"] as Array<*>?
                    if (pdus != null) {
                        for (pdu in pdus) {
                            val message = SmsMessage.createFromPdu(pdu as ByteArray)
                            val sender = message.originatingAddress
                            val messageBody = message.messageBody
                            val time = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())
                            
                            // 获取SIM卡信息
                            val simInfo = getSimInfo(context, intent)
                            Log.d(TAG, "新短信 - 发送者: $sender, 内容: $messageBody, SIM卡信息: $simInfo")
                            
                            // 使用WorkManager调度邮件发送任务
                            scheduleEmailForwarding(context, sender, messageBody, time, simInfo)
                            
                            // 只处理第一条短信即可，避免重复发送邮件
                            break
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 获取接收短信的SIM卡信息
     */
    private fun getSimInfo(context: Context, intent: Intent): String {
        try {
            // // 方法1：尝试从intent中直接获取subscription_id
            // val subscriptionId = intent.getIntExtra("subscription_id", -1)
            // if (subscriptionId != -1) {
            //     Log.d(TAG, "直接从Intent获取到subscription_id: $subscriptionId")
            //     return getSimInfoFromSubscriptionId(context, subscriptionId)
            // }
            
            // 方法2：尝试从intent中获取slot信息
            val slotIndex = intent.getIntExtra("slot_id", -1)
            if (slotIndex != -1) {
                Log.d(TAG, "直接从Intent获取到slot_index: $slotIndex")
                return "SIM" + (slotIndex + 1)
            }
            
            // // 方法3：尝试从intent中获取subscription信息
            // val subscription = intent.getIntExtra("subscription", -1)
            // if (subscription != -1) {
            //     Log.d(TAG, "从Intent获取到subscription: $subscription")
            //     return getSimInfoFromSubscriptionId(context, subscription)
            // }
            
            // 方法4：对于Android 6.0及以上版本，我们可以使用SubscriptionManager获取SIM卡信息
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                try {
                    val subscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
                    // 获取所有活动的SIM卡订阅
                    val activeSubscriptionInfoList = subscriptionManager.activeSubscriptionInfoList
                    if (activeSubscriptionInfoList != null && activeSubscriptionInfoList.isNotEmpty()) {
                        Log.d(TAG, "获取到${activeSubscriptionInfoList.size}个活动的SIM卡订阅")
                        // 如果无法确定具体是哪个SIM卡，至少返回第一个活动的SIM卡信息
                        val firstSubscription = activeSubscriptionInfoList[0]
                        return firstSubscription.carrierName.toString() + " (SIM" + firstSubscription.simSlotIndex + ")"
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "通过SubscriptionManager获取SIM卡信息失败: ${e.message}")
                }
            }
            
            // 方法5：通过反射获取SIM卡信息
            val pdus = intent.getSerializableExtra("pdus") as? Array<*>?
            if (pdus != null && pdus.isNotEmpty()) {
                try {
                    val smsMessage = SmsMessage.createFromPdu(pdus[0] as ByteArray)
                    
                    // 尝试多种反射方法
                    // 方法5.1：尝试获取slot信息
                    try {
                        val messageClass = smsMessage.javaClass
                        val getSlotMethod = messageClass.getMethod("getSlot")
                        val slotId = getSlotMethod.invoke(smsMessage) as Int
                        return "SIM" + (slotId + 1)
                    } catch (e: Exception) {
                        Log.w(TAG, "反射获取getSlot方法失败: ${e.message}")
                    }
                    
                    // 方法5.2：尝试获取slotIndex信息
                    try {
                        val messageClass = smsMessage.javaClass
                        val getSlotIndexMethod = messageClass.getMethod("getSlotIndex")
                        val slotIndex = getSlotIndexMethod.invoke(smsMessage) as Int
                        return "SIM" + (slotIndex + 1)
                    } catch (e: Exception) {
                        Log.w(TAG, "反射获取getSlotIndex方法失败: ${e.message}")
                    }
                    
                    // 方法5.3：尝试获取subId信息
                    try {
                        val messageClass = smsMessage.javaClass
                        val getSubIdMethod = messageClass.getMethod("getSubId")
                        val subId = getSubIdMethod.invoke(smsMessage) as Int
                        return getSimInfoFromSubscriptionId(context, subId)
                    } catch (e: Exception) {
                        Log.w(TAG, "反射获取getSubId方法失败: ${e.message}")
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "通过反射获取SIM卡信息失败: ${e.message}")
                }
            }
            
            // 记录所有intent额外数据，便于调试
            val extras = intent.extras
            if (extras != null) {
                val keys = extras.keySet()
                val stringBuilder = StringBuilder()
                for (key in keys) {
                    stringBuilder.append("$key: ${extras.get(key)}\n")
                }
                Log.d(TAG, "Intent中所有额外数据:\n$stringBuilder")
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取SIM卡信息失败: ${e.message}")
            e.printStackTrace()
        }
        
        // 默认返回未知SIM卡
        return "未知SIM卡"
    }
    
    /**
     * 通过subscriptionId获取SIM卡信息
     */
    private fun getSimInfoFromSubscriptionId(context: Context, subscriptionId: Int): String {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val subscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
                val subscriptionInfo = subscriptionManager.getActiveSubscriptionInfo(subscriptionId)
                if (subscriptionInfo != null) {
                    return subscriptionInfo.carrierName.toString() + " (SIM" + subscriptionInfo.simSlotIndex + ")"
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "通过subscriptionId获取SIM卡信息失败: ${e.message}")
        }
        
        return "SIM卡信息(subscriptionId: $subscriptionId)"
    }
    
    /**
     * 使用WorkManager调度邮件发送任务
     */
    private fun scheduleEmailForwarding(context: Context, sender: String?, content: String, time: String, simInfo: String) {
        try {
            // 创建WorkRequest
            val workRequest: WorkRequest = OneTimeWorkRequestBuilder<SmsForwardWorker>()
                // 添加输入数据
                .setInputData(
                    androidx.work.Data.Builder()
                        .putString(SmsForwardWorker.KEY_SENDER, sender)
                        .putString(SmsForwardWorker.KEY_CONTENT, content)
                        .putString(SmsForwardWorker.KEY_TIME, time)
                        .putString(SmsForwardWorker.KEY_SIM_INFO, simInfo)
                        .build()
                )
                // 设置重试策略
                .setBackoffCriteria(
                    androidx.work.BackoffPolicy.EXPONENTIAL,
                    WorkRequest.MIN_BACKOFF_MILLIS,
                    TimeUnit.MILLISECONDS
                )
                // 设置初始延迟（立即执行）
                .setInitialDelay(0, TimeUnit.MILLISECONDS)
                .build()

            // 提交任务到WorkManager
            WorkManager.getInstance(context).enqueue(workRequest)
            Log.d(TAG, "邮件转发任务已调度")
        } catch (e: Exception) {
            Log.e(TAG, "调度邮件转发任务失败", e)
            // 任务调度失败，创建本地通知提醒用户
            showNotification(context, "短信转发失败", "无法调度邮件转发任务，请检查应用状态")
        }
    }

    /**
     * 显示本地通知
     */
    private fun showNotification(context: Context, title: String, content: String) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 创建通知渠道
                val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
                val channel = android.app.NotificationChannel(
                    "SMS_FORWARDING_CHANNEL",
                    "短信转发",
                    android.app.NotificationManager.IMPORTANCE_DEFAULT
                )
                notificationManager.createNotificationChannel(channel)
            }

            // 创建通知
            val notification = android.app.Notification.Builder(context, "SMS_FORWARDING_CHANNEL")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(title)
                .setContentText(content)
                .setPriority(android.app.Notification.PRIORITY_DEFAULT)
                .setAutoCancel(true)
                .build()

            // 显示通知
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
            notificationManager.notify(System.currentTimeMillis().toInt(), notification)
        } catch (e: Exception) {
            Log.e(TAG, "显示通知失败", e)
        }
    }
}